<template>
  <div class="bar-chart-container" :style="{ width: (isDemo ? testData.width : props.width) + 'px', height: (isDemo ? testData.height : props.height) + 'px', background: (isDemo ? testData.bgColor : props.bgColor) || 'none' }" ref="chartRef">
    
    <div v-if="isEmpty" class="chart-empty">暂无数据</div>
    <div v-if="loading" class="chart-loading">加载中...</div>

  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import * as echarts from 'echarts'
import { merge } from 'lodash-es'
import { ComponentInstance } from '@/types/visual-app';

const emit = defineEmits(['bar-click'])
const props = defineProps<ComponentInstance>()

const isDemo=ref<boolean>(true)

const testData={
  "id": "bar-chart-001",
  "type": "BarChart",
  "name": "柱状图",
  "width": 400,
  "height": 300,
  "bgColor":'#0e0e0e',
  "config": {
    "attributes": {
      "title": "销售数据统计",
      "props": {
        "categories": ["1月", "2月", "3月", "4月", "5月", "6月"],
        "series": [
          {
            "name": "销售额",
            "data": [120, 200, 150, 80, 70, 110],
            "color": "#409eff"
          },
          {
            "name": "利润",
            "data": [20, 40, 30, 15, 12, 25],
            "color": "#67c23a"
          }
        ],
        "showValue": true,
        "valueFormat": "number",
        "precision": 2,
        "colors": ["#409eff", "#67c23a", "#e6a23c", "#f56c6c", "#909399"],
        "option": {
          "grid": {
            "left": "3%",
            "right": "4%",
            "bottom": "3%",
            "containLabel": true
          }
        }
      }
    }
  }
}


// 本地状态管理
const localCategories = ref<string[]>([])
const localSeries = ref<Array<{ name: string; data: number[]; color?: string }>>([])
const localShowValue = ref<boolean>(false)
const localValueFormat = ref<'number' | 'percent' | 'currency'>('number')
const localPrecision = ref<number>(2)
const localColors = ref<string[]>(['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399'])
const localOption = ref<any>({})

// 监听props变更，实时同步参数
watch(
  () => isDemo.value ? testData.config?.attributes?.props : props.config?.attributes?.props,
  (val) => {
    console.log('BarChart watch triggered:', {
      isDemo: isDemo.value,
      val,
      testData: testData.config?.attributes?.props,
      props: props.config?.attributes?.props
    })
    
    if (val?.props) {
      // 同步分类数据
      if (Array.isArray(val.props.categories)) {
        localCategories.value = val.props.categories
        console.log('Categories synced:', localCategories.value)
      }
      
      // 同步系列数据
      if (Array.isArray(val.props.series)) {
        localSeries.value = val.props.series
        console.log('Series synced:', localSeries.value)
      }
      
      // 同步显示值设置
      if (typeof val.props.showValue === 'boolean') {
        localShowValue.value = val.props.showValue
      }
      
      // 同步值格式
      if (val.props.valueFormat && ['number', 'percent', 'currency'].includes(val.props.valueFormat)) {
        localValueFormat.value = val.props.valueFormat as 'number' | 'percent' | 'currency'
      }
      
      // 同步精度
      if (typeof val.props.precision === 'number') {
        localPrecision.value = val.props.precision
      }
      
      // 同步颜色
      if (Array.isArray(val.props.colors)) {
        localColors.value = val.props.colors
      }
      
      // 同步自定义配置
      if (val.props.option && typeof val.props.option === 'object') {
        localOption.value = val.props.option
      }
    } else {
      console.warn('No valid props data found')
    }
  },
  { immediate: true, deep: true }
)

// 添加一个立即执行的初始化函数
const initializeData = () => {
  if (isDemo.value) {
    const demoProps = testData.config?.attributes?.props
    if (demoProps) {
      console.log('Initializing with demo data:', demoProps)
      
      if (Array.isArray(demoProps.categories)) {
        localCategories.value = demoProps.categories
      }
      
      if (Array.isArray(demoProps.series)) {
        localSeries.value = demoProps.series
      }
      
      if (typeof demoProps.showValue === 'boolean') {
        localShowValue.value = demoProps.showValue
      }
      
      if (demoProps.valueFormat && ['number', 'percent', 'currency'].includes(demoProps.valueFormat)) {
        localValueFormat.value = demoProps.valueFormat as 'number' | 'percent' | 'currency'
      }
      
      if (typeof demoProps.precision === 'number') {
        localPrecision.value = demoProps.precision
      }
      
      if (Array.isArray(demoProps.colors)) {
        localColors.value = demoProps.colors
      }
      
      if (demoProps.option && typeof demoProps.option === 'object') {
        localOption.value = demoProps.option
      }
    }
  }
}

// 立即执行初始化
initializeData()

const chartRef = ref<HTMLDivElement | null>(null)
let chart: echarts.ECharts | null = null
const loading = ref(false)

// 修复 isEmpty 计算属性的逻辑
const isEmpty = computed(() => {
  const is = !Array.isArray(localSeries.value) || 
         localSeries.value.length === 0 ||
         localSeries.value.every(s => !Array.isArray(s.data) || s.data.length === 0)
  
  console.log('isEmpty check:', {
    localSeries: localSeries.value,
    isArray: Array.isArray(localSeries.value),
    length: localSeries.value?.length,
    is
  })
  
  return is
})

function formatValue(value: number): string {
  // 添加类型检查
  if (typeof value !== 'number' || isNaN(value)) {
    console.warn('formatValue received invalid value:', value)
    return '0'
  }

  switch (localValueFormat.value) {
    case 'percent': 
      return (value * 100).toFixed(localPrecision.value) + '%'
    case 'currency': 
      return '¥' + value.toFixed(localPrecision.value)
    default: 
      return value.toFixed(localPrecision.value)
  }
}

function getOption() {
  const safeSeries = Array.isArray(localSeries.value) ? localSeries.value : []
  const safeCategories = Array.isArray(localCategories.value) ? localCategories.value : []
  
  // 根据 isDemo 状态获取标题
  const title = isDemo.value 
    ? testData.config?.attributes?.title 
    : props.config?.attributes?.title
  
  return merge({}, {
    title: title ? { 
      text: title, 
      left: 'center', 
      top: 10 
    } : undefined,
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any) => {
        let html = ''
        if (params[0]) {
          html += `<div style='font-weight:600;margin-bottom:4px;'>${params[0].axisValue}</div>`
        }
        params.forEach((item: any) => {
          html += `<div>
            <span style="display:inline-block;width:10px;height:10px;background:${item.color};margin-right:6px;border-radius:2px;"></span>
            ${item.seriesName}：${formatValue(item.data)}
          </div>`
        })
        return html
      }
    },
    legend: { 
      show: safeSeries.length > 1, 
      top: 30 
    },
    grid: { 
      left: 40, 
      right: 20, 
      top: 60, 
      bottom: 40 
    },
    xAxis: { 
      type: 'category', 
      data: safeCategories, 
      axisTick: { alignWithLabel: true } 
    },
    yAxis: { 
      type: 'value', 
      axisLabel: { 
        formatter: (value: number) => formatValue(value) 
      } 
    },
    series: safeSeries.map((s, i) => ({
      name: s.name,
      type: 'bar',
      data: Array.isArray(s.data) ? s.data : [],
      itemStyle: { 
        color: s.color || localColors.value[i % localColors.value.length] 
      },
      label: localShowValue.value
        ? { 
            show: true, 
            position: 'top', 
            formatter: (params: any) => formatValue(params.value), 
            fontSize: 12 
          }
        : { show: false }
    }))
  }, localOption.value)
}

function renderChart() {
  console.log('renderChart called:', {
    chartRef: !!chartRef.value,
    chart: !!chart,
    localSeries: localSeries.value,
    localCategories: localCategories.value
  })
  
  if (!chartRef.value) {
    console.warn('chartRef is null')
    return
  }
  
  const w = chartRef.value.clientWidth
  const h = chartRef.value.clientHeight
  console.log('Container dimensions:', { width: w, height: h })
  
  if (w === 0 || h === 0) {
    console.log('Container has zero dimensions, retrying...')
    setTimeout(renderChart, 100)
    return
  }
  
  if (!chart) {
    console.log('Initializing chart...')
    chart = echarts.init(chartRef.value)
    chart.on('click', params => emit('bar-click', params))
  }
  
  const option = getOption()
  console.log('Chart option:', option)
  
  chart.setOption(option, true)
  console.log('Chart rendered successfully')
}

function resizeChart() {
  chart?.resize()
}

onMounted(() => {
  nextTick(() => {
    renderChart()
    window.addEventListener('resize', resizeChart)
  })
})

// 监听数据变化，重新渲染图表
watch(
  () => [localCategories.value, localSeries.value, localShowValue.value, localValueFormat.value, localPrecision.value, localColors.value, localOption.value],
  () => {
    nextTick(() => {
      renderChart()
    })
  },
  { deep: true }
)

// 监听容器尺寸变化
watch(
  () => isDemo.value ? [testData.width, testData.height] : [props.width, props.height],
  () => {
    nextTick(() => {
      resizeChart()
    })
  }
)

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  chart?.dispose()
  chart = null
})

defineExpose({
  resize: resizeChart,
  refresh: renderChart,
  getChart: () => chart
})
</script>

<style scoped>
.bar-chart-container {
  width: 100%;
  height: 100%;
  min-width: 100px;
  min-height: 80px;
}

.chart-loading, .chart-empty {
  position: absolute;
  left: 0; 
  top: 0; 
  right: 0; 
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 15px;
  background: rgba(255,255,255,0.7);
  z-index: 2;
}
</style>

<!--
BarChart 组件配置 JSON 格式示例：

{
  "id": "bar-chart-001",
  "type": "BarChart",
  "name": "柱状图",
  "width": 400,
  "height": 300,
  "config": {
    "attributes": {
      "title": "销售数据统计",
      "props": {
        "categories": ["1月", "2月", "3月", "4月", "5月", "6月"],
        "series": [
          {
            "name": "销售额",
            "data": [120, 200, 150, 80, 70, 110],
            "color": "#409eff"
          },
          {
            "name": "利润",
            "data": [20, 40, 30, 15, 12, 25],
            "color": "#67c23a"
          }
        ],
        "showValue": true,
        "valueFormat": "number",
        "precision": 2,
        "colors": ["#409eff", "#67c23a", "#e6a23c", "#f56c6c", "#909399"],
        "option": {
          "grid": {
            "left": "3%",
            "right": "4%",
            "bottom": "3%",
            "containLabel": true
          }
        }
      }
    }
  }
}

配置说明：
- categories: 分类数据数组，对应 X 轴标签
- series: 系列数据数组，每个系列包含 name(名称)、data(数据)、color(颜色，可选)
- showValue: 是否显示数值标签
- valueFormat: 数值格式，支持 'number'|'percent'|'currency'
- precision: 数值精度，小数位数
- colors: 默认颜色数组，当系列没有指定颜色时使用
- option: 自定义 ECharts 配置，会与默认配置合并
-->